<script lang="ts" setup>
import { ref } from 'vue'

import AdvancedTable from '@/components/sofastui/AdvancedTable/AdvancedTable.vue'
import AdvancedForm from '@/components/sofastui/AdvancedForm/AdvancedForm.vue'
import AdvancedTree from '@/components/sofastui/AdvancedTree/AdvancedTree.vue'
import LTreeTable from '@/components/layout/LTreeTable.vue'

import { fields, config, formRules } from './constant'

const advancedFormRef = ref()
const advancedTableRef = ref()

const searchFormData = ref<{
  orgId?: number | null
}>({})

// 创建
const handelAdd = () => {
  advancedFormRef.value?.show('add', {
    orgId: searchFormData.value.orgId,
  })
}

// 行展开
const handelRowExpand = (data: { [key: string]: unknown }) => {
  advancedFormRef.value?.show('update', data)
}

// 树点击
const handelTreeClick = (data: { id: number }) => {
  searchFormData.value.orgId = data?.id
}

// 刷新表格数据
const refreshTableData = () => {
  advancedTableRef.value!.refresh()
}
</script>

<template>
  <LTreeTable>
    <template #tree>
      <AdvancedTree
        :config="{
          url: '/api/idt/org/tree',
          method: 'get',
        }"
        :tree-props="{
          label: 'name',
        }"
        @node-click="handelTreeClick"
      />
    </template>

    <template #table>
      <AdvancedTable
        ref="advancedTableRef"
        :query="searchFormData"
        :fields="fields"
        :config="config"
        @add="handelAdd"
        @rowExpand="handelRowExpand"
      >
        <template #roles="scope">{{
          scope.row.roles.map((item: any) => item.name).join(',')
        }}</template>
        <template #jobs="scope">{{
          scope.row.jobs.map((item: any) => item.name).join(',')
        }}</template>
      </AdvancedTable>
    </template>
  </LTreeTable>

  <!-- 修改表单 -->
  <AdvancedForm
    ref="advancedFormRef"
    :config="config"
    :rule="formRules"
    @success="refreshTableData"
  />
</template>
